import Taro from "@tarojs/taro";
import { from, switchMap } from "rxjs";
import { subsOrderParam } from "@/models/request/userReq";
import subsService from "@/services/subsService";

//主要用于比较微信基础库版本号，返回1代表v1>v2，返回0代表相等，返回-1代表v1<v2
function compareVersion(v1: string, v2: string) {
  const v1Arr = v1.split('.');
  const v2Arr = v2.split('.');

  const len = Math.max(v1Arr.length, v2Arr.length);

  while (v1Arr.length < len) {
    v1Arr.push('0');
  }
  while (v2Arr.length < len) {
    v2Arr.push('0');
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1Arr[i]);
    const num2 = parseInt(v2Arr[i]);

    if (num1 > num2) {
      return 1;
    } else if (num1 < num2) {
      return -1;
    }
  }

  return 0;
}

//创建订阅订单
function createSubsOrder(param: subsOrderParam) { 
  return subsService.subsOrderSvc(param)
    .pipe(
      switchMap(rsp => from(Taro.requestPayment({
        timeStamp: rsp.timeStamp,
        nonceStr: rsp.nonceStr,
        package: rsp.package,
        signType: rsp.signType,
        paySign: rsp.paySign
      })))
    )
} 
 
export {
  compareVersion,
  createSubsOrder
}